import store from "@/store";
import path from "path-browserify";

// 开发环境不使用懒加载, 因为懒加载页面太多的话会造成webpack热更新太慢, 所以只有生产环境使用懒加载
// const _import = require("./import-" + process.env.NODE_ENV);

const layout = import("@/layout");
/**
 *  添加动态路由
 * @param {*} router 路由
 */
async function addDynamicMenuRoutes(router) {
	//获取用户信息
	store.dispatch("user/fetchUserInfo");

	let menus = await store.dispatch("user/fetchMenus");

	//编译动态路由
	let dynamicMenuRoutes = buildAsyncRouter(menus, "/", layout);

	//设置面包屑
	flatAsyncRoutes(dynamicMenuRoutes);

	// 加入router
	for (let menu of dynamicMenuRoutes) {
		router.addRoute(menu);
	}

	// console.log(
	// 	"addDynamicMenuRoutes router.getRoutes()",
	// 	dynamicMenuRoutes,
	// 	router.getRoutes()
	// );
	//设置store
	console.log("addDynamicMenuRoutes", dynamicMenuRoutes);
	store.dispatch("user/setMenus", dynamicMenuRoutes);
}

//转换
function buildAsyncRouter(menus, basePath, defaultComponent) {
	if (!menus) {
		return [];
	}
	let accessedRouters = [];

	for (let menu of menus) {
		// console.log("buildAsyncRouter menu", menu.name, menu);
		menu.name = menu.name ? menu.name : menu.menuId;
		menu.meta = menu.meta ? menu.meta : {};
		menu.meta.menuId = menu.menuId;
		menu.redirect = null;
		let component;
		let route;
		//是否有子菜单
		menu.noChildrenMenu = !hasChildrenMenu(menu);
		//链接处理
		if (menu.meta.menuType == 11 || menu.meta.menuType == 10) {
			menu.meta.url = menu.component;
			menu.component = null;
		}
		//处理内部链接
		if (menu.meta.menuType == 10) {
			component = iframeComponent;
		} else if (menu.meta.menuType === 30) {
			//重定向
			menu.redirect = menu.component;
			menu.component = null;
		} else {
			component = loadComponent(menu.component);
		}

		// if (menu.meta && menu.meta.title) {
		// 	menu.meta.title = i18n.t(menu.meta.title);
		// }
		//解析成绝对路径
		basePath = path.resolve(basePath, menu.path);
		let children = menu.children
			? buildAsyncRouter(menu.children, basePath)
			: null;
		//MAP转路由对象

		//没有子菜单，作为一级菜单,使用layout作为基础布局
		if (defaultComponent && menu.noChildrenMenu) {
			route = {
				path: basePath,
				name: "_" + menu.name,
				meta: menu.meta,
				children: children,
				component: defaultComponent,
				noChildrenMenu: true,
			};

			route.children = [
				{
					path: "",
					name: menu.name,
					meta: menu.meta,
					redirect: menu.redirect,
					// children: children,
					component: component,
				},
			];
			console.log("addDynamicMenuRoutes noChildrenMenu", route);
		} else {
			route = {
				path: basePath,
				name: menu.name,
				meta: menu.meta,
				redirect: menu.redirect,
				children: children,
				component: menu.noChildrenMenu ? component : defaultComponent,
				noChildrenMenu: menu.noChildrenMenu,
			};
		}
		route.menuId = menu.menuId;
		accessedRouters.push(route);
	}
	return accessedRouters;
}

function loadComponent(component) {
	if (component) {
		return () => import(`@/views/${component}`);
	} else {
		return null;
	}
}

/**
 * 是否有子路由
 * @param {*} menu
 * @returns
 */
function hasChildrenMenu(menu) {
	// console.log("hasChildren", item);
	return menu.children && !menu.children.every((menu) => menu.hidden);
}

//路由扁平化, 设置面包屑 TODO
function flatAsyncRoutes(routes, breadcrumb = []) {
	let res = [];
	routes.forEach((route) => {
		const tmp = { ...route };
		if (!tmp.meta) {
			return;
		}
		if (tmp.children) {
			let childrenBreadcrumb = [...breadcrumb];
			childrenBreadcrumb.push(route);
			let tmpRoute = { ...route };

			tmpRoute.meta.breadcrumb = childrenBreadcrumb;
			delete tmpRoute.children;
			res.push(tmpRoute);
			let childrenRoutes = flatAsyncRoutes(
				tmp.children,
				childrenBreadcrumb
			);
			childrenRoutes.map((item) => {
				res.push(item);
			});
		} else {
			let tmpBreadcrumb = [...breadcrumb];
			tmpBreadcrumb.push(tmp);
			tmp.meta.breadcrumb = tmpBreadcrumb;
			route.meta.breadcrumb = tmpBreadcrumb;
			res.push(tmp);
		}
	});
	return res;
}

/**
 * iframe 组件
 */
function iframeComponent() {
	return import("@/layout/components/iframeView.vue");
}
export default addDynamicMenuRoutes;
